package com.ss.android.d;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

import com.bytedance.common.utility.Logger;
import com.bytedance.common.utility.collection.WeakHandler;
import com.ss.android.model.AbsArticle;
import com.ss.android.model.ItemActionV3;
import com.ss.android.model.ItemType;
import com.ss.android.model.b;
import com.ss.android.model.ItemAction;
import com.ss.android.model.BaseArticle;
import com.ss.android.model.f;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public abstract class SSDBHelper implements WeakHandler.Callback {
    public final class a$a {
        public a$a() {

        }
    }

    public SQLiteDatabase mSQLiteDatabase;
    private Context mContext;
    private volatile boolean c;
    private HandlerThread mAsyncOpThread;
    private final Handler mAsyncOpHandler;

    public SSDBHelper(Context context) {
        this.c = false;
        this.mContext = context;
        this.mAsyncOpThread = new HandlerThread("DBHelper-AsyncOp");
        this.mAsyncOpThread.start();
        this.mAsyncOpHandler = new WeakHandler(this.mAsyncOpThread.getLooper(), this);
    }

    public final void a(int arg7, long userRepinTs, AbsArticle absArticle) {
        if (absArticle != null && this.a(absArticle.opItemType) != null) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("ss_op_key", Integer.valueOf(1));
            contentValues.put("op_item_type", Integer.valueOf(absArticle.opItemType.getValue()));
            contentValues.put("item_id", Long.valueOf(absArticle.groupId));
            contentValues.put("group_item_id", Long.valueOf(absArticle.itemId));
            contentValues.put("tag", absArticle.tag);
            switch (arg7) {
                case 1:
                case 2:
                    contentValues.put("user_digg", Integer.valueOf(absArticle.userDigg ? 1 : 0));
                    contentValues.put("user_bury", Integer.valueOf(absArticle.userBury ? 1 : 0));
                    contentValues.put("digg_count", Integer.valueOf(absArticle.diggCount));
                    contentValues.put("bury_count", Integer.valueOf(absArticle.buryCount));
                    break;
                case 4:
                case 5:
                    absArticle.userRepinTime = userRepinTs / 1000;
                    contentValues.put("user_repin", Integer.valueOf(absArticle.userRepin ? 1 : 0));
                    contentValues.put("user_repin_time", Long.valueOf(absArticle.userRepinTime));
                    contentValues.put("repin_count", Integer.valueOf(absArticle.repinCount));
                    break;
                case 9:
                case 10:
                    contentValues.put("user_dislike", Integer.valueOf(absArticle.userDislike ? 1 : 0));
                    break;
                default:
                    return;
            }
            this.asyncUpdate(contentValues);
        }
    }

    public final void asyncUpdate(ContentValues contentValues) {
        if (contentValues != null) {
            this.mAsyncOpHandler.sendMessage(this.mAsyncOpHandler.obtainMessage(10, contentValues));
        }
    }

    public abstract a$a a(ItemType itemType);

    public final void a(ItemActionV3 itemActionV3) {
        if (itemActionV3 != null) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("ss_op_key", Integer.valueOf(5));
            contentValues.put("group_id", Long.valueOf(itemActionV3.d.groupId));
            contentValues.put("item_id", Long.valueOf(itemActionV3.d.itemId));
            contentValues.put("aggr_type", Integer.valueOf(itemActionV3.d.aggrType));
            contentValues.put("action", itemActionV3.action);
            contentValues.put("timestamp", Long.valueOf(itemActionV3.timestamp));
            contentValues.put("target_type", Integer.valueOf(itemActionV3.targetType));
            contentValues.put("extra_data", itemActionV3.json);
            this.asyncUpdate(contentValues);
        }
    }

    public void a(f arg1) {
    }

    public final void updateImpressionData(List arg13, boolean arg14) {
        String v7;
        long v8;
        int v6;
        String v5;
        Object v0_2;
        String[] v3;
        String v2;
        int v1 = 1;
        synchronized (this) {
            if (arg13 != null) {
                if (arg13.isEmpty()) {
                    return;
                }
                if (this.mSQLiteDatabase == null) {
                    return;
                }

                if (!this.isSQLiteDatabaseAvailable()) {
                    return;
                }

                if (!this.isTableExists("impression")) {
                    return;
                }

                this.mSQLiteDatabase.beginTransaction();

                try {
                    v2 = "key_name=? AND list_type=? AND session_id=?";
                    v3 = new String[]{"", "", ""};
                    Iterator v4 = arg13.iterator();
                    while (true) {
                        if (!v4.hasNext()) {
                            break;
                        }
                        v0_2 = v4.next();
                        v5 = ((b) v0_2).keyName;
                        v6 = ((b) v0_2).listType;
                        v8 = ((b) v0_2).sessionId;
                        v7 = ((b) v0_2).extra;
                        if (!android.support.design.a.isTextEmpty(v5)) {
                            if (((b) v0_2).jsonArray != null && ((b) v0_2).jsonArray.length() > 0) {
                                String v0_3 = ((b) v0_2).jsonArray.toString();
                                v3[0] = v5;
                                v3[1] = String.valueOf(v6);
                                v3[2] = String.valueOf(v8);
                                this.mSQLiteDatabase.delete("impression", v2, v3);
                                if (arg14) {
                                    ContentValues contentValues = new ContentValues();
                                    contentValues.put("key_name", v5);
                                    contentValues.put("list_type", Integer.valueOf(v6));
                                    contentValues.put("impression", v0_3);
                                    contentValues.put("session_id", Long.valueOf(v8));
                                    contentValues.put("extra", v7);
                                    this.mSQLiteDatabase.insert("impression", null, contentValues);
                                }
                                continue;
                            } else {
                                try {
                                    if (this.mSQLiteDatabase == null) {
                                        return;
                                    }

                                    try {
                                        this.mSQLiteDatabase.endTransaction();
                                    } catch (Exception v0_1) {
                                    }
                                    return;
                                } catch (Throwable v0) {
                                    return;
                                }
                            }
                        }
                        try {
                            if (this.mSQLiteDatabase == null) {
                                return;
                            }

                            try {
                                this.mSQLiteDatabase.endTransaction();
                            } catch (Exception v0_1) {
                            }
                            return;
                        } catch (Throwable v0) {

                        }
                    }

                    try {
                        this.mSQLiteDatabase.setTransactionSuccessful();
                        if (this.mSQLiteDatabase == null) {
                            return;
                        }

                        try {
                            this.mSQLiteDatabase.endTransaction();
                        } catch (Exception v0_1) {
                        }
                        return;
                    } catch (Throwable v0) {

                    }
                } catch (Exception v0_1) {
                    Logger.w("SSDBHelper", "updateImpressionData exception: " + v0_1);
                } finally {
                    try {
                        this.mSQLiteDatabase.endTransaction();
                    } catch (Exception v0_1) {
                    }

                    try {

                    } catch (Exception e) {

                    }
                }
            }
        }
    }

    public final void a(long sessionId, List arg14) {
        String extra;
        String impression;
        int listType;
        String keyName;
        Cursor cursor = null;
        String[] id;
        Cursor v9 = null;
        synchronized (this) {
            if (sessionId <= 0) {
                return;
            }

            if (arg14 == null) {
                return;
            }

            try {
                if (!this.isSQLiteDatabaseAvailable()) {
                    return;
                }

                if (!this.isTableExists("impression")) {
                    return;
                }

                id = new String[]{String.valueOf(sessionId)};
                cursor = this.mSQLiteDatabase.query("impression", new String[]{"key_name", "list_type", "impression", "extra"},
                        "session_id=?", id, null, null, null, "200");
                while (true) {
                    if (!cursor.moveToNext()) {
                        this.mSQLiteDatabase.delete("impression", "session_id<=?", id);
                        break;
                    }

                    keyName = cursor.getString(0);
                    listType = cursor.getInt(1);
                    impression = cursor.getString(2);
                    extra = cursor.getString(3);
                    if (android.support.design.a.isTextEmpty(keyName)) {
                        continue;
                    }
                    try {
                        JSONArray jsonArray = new JSONArray(impression);
                        if (jsonArray.length() <= 0) {
                            continue;
                        }

                        b v3_1 = new b();
                        v3_1.keyName = keyName;
                        v3_1.listType = listType;
                        v3_1.sessionId = sessionId;
                        v3_1.jsonArray = jsonArray;
                        v3_1.extra = extra;
                        arg14.add(v3_1);
                    } catch (Exception v1) {
                    }
                    continue;
                }
            } catch (Exception v1) {

            } finally {
                if (cursor != null) {
                    try {
                        cursor.close();
                    } catch (Exception e) {

                    }
                }
            }
        }
    }

    public static void closeQuietly(Cursor cursor) {
        if (cursor != null) {
            try {
                if (cursor.isClosed()) {
                    return;
                }
                cursor.close();
            } catch (Exception exception) {
            }
        }
    }

    public static void closeQuietlyAndEndTransaction(Cursor cursor, SQLiteDatabase database) {
        closeQuietly(cursor);
        if (database != null) {
            try {
                if (database.inTransaction()) {
                    database.endTransaction();
                }
            } catch (Exception exception) {
            }
        }
    }

    private boolean isTableExists(String tableName) {
        int v3;
        Cursor cursor = null;
        if (!android.support.design.a.isTextEmpty(tableName)) {
            try {
                cursor = this.mSQLiteDatabase.rawQuery("SELECT count(*) FROM sqlite_master WHERE type=\'table\' AND name=?", new String[]{tableName});
                if (cursor.moveToNext()) {
                    v3 = cursor.getInt(0);
                } else {
                    v3 = 0;
                }
                if (v3 <= 0) {
                    return false;
                }
                return true;
            } catch (Exception e) {
                Logger.w("SSDBHelper", "isTableExists exception: " + e);
            } finally {
                if (cursor != null) {
                    try {
                        cursor.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
        return false;
    }

    public void a(int arg13, ContentValues arg14) {
        if (arg14 != null && arg14.size() != 0) {
            int v0 = 0;
            Long v1;
            Integer v2;
            switch (arg13) {
                case 1: {
                    v1 = arg14.getAsLong("item_id");
                    if (v1 == null) {
                        return;
                    }

                    if (v1.longValue() <= 0) {
                        return;
                    }

                    Long v0_1 = Long.valueOf(0);
                    if (arg14.containsKey("group_item_id")) {
                        v0_1 = arg14.getAsLong("group_item_id");
                    }

                    v2 = arg14.getAsInteger("op_item_type");
                    if (v2 == null) {
                        return;
                    }

                    ItemType v2_1 = ItemType.fromValue(v2.intValue());
                    if (v2_1 == null) {
                        return;
                    }

                    if (this.a(v2_1) == null) {
                        return;
                    }

                    String v3_1 = "item_id =? AND group_item_id =?";
                    String[] v4_1 = new String[]{String.valueOf(v1), String.valueOf(v0_1)};
                    arg14.remove("op_item_type");
                    arg14.remove("item_id");
                    arg14.remove("group_item_id");
                    arg14.remove("tag");
                    if (arg14.size() <= 0) {
                        return;
                    }

                    String v0_2 = this.b(v2_1);
                    if (android.support.design.a.isTextEmpty(v0_2)) {
                        return;
                    }

                    this.mSQLiteDatabase.update(v0_2, arg14, v3_1, v4_1);
                    return;
                }
                case 4: {
                    v0 = 1;
                }
                case 3: {
                    Long v3 = arg14.getAsLong("item_id");
                    if (v3 != null && v3.longValue() > 0) {
                        v1 = Long.valueOf(0);
                        v2 = Integer.valueOf(0);
                        if (arg14.containsKey("group_item_id")) {
                            v1 = arg14.getAsLong("group_item_id");
                        }

                        if (arg14.containsKey("aggr_type")) {
                            v2 = arg14.getAsInteger("aggr_type");
                        }

                        Integer v4 = arg14.getAsInteger("action");
                        if (v4 == null) {
                            return;
                        }

                        if (v4.intValue() <= 0) {
                            return;
                        }

                        Long v5 = arg14.getAsLong("timestamp");
                        if (v5 == null) {
                            return;
                        }

                        if (v5.longValue() <= 0) {
                            return;
                        }

                        if (v0 != 0) {
                            this.mSQLiteDatabase.delete("item_action", "item_id=? AND group_item_id=? AND action=? AND timestamp=?", new String[]{String.valueOf(v3), String.valueOf(v1), String.valueOf(v4), String.valueOf(v5)});
                            return;
                        }

                        String[] v6 = new String[]{String.valueOf(v3), String.valueOf(v1), String.valueOf(v4)};
                        arg14.clear();
                        arg14.put("timestamp", v5);
                        if (this.mSQLiteDatabase.update("item_action", arg14, "item_id=? AND group_item_id=? AND action=?", v6) > 0) {
                            return;
                        }

                        arg14.put("item_id", v3);
                        arg14.put("group_item_id", v1);
                        arg14.put("aggr_type", v2);
                        arg14.put("action", v4);
                        this.mSQLiteDatabase.insert("item_action", null, arg14);
                        return;
                    }
                    break;
                }
                case 6: {
                    v0 = 1;
                }
                case 5: {
                    if (!this.isTableExists("item_action_v3")) {
                        return;
                    }

                    String v4_2 = arg14.getAsString("action");
                    if (android.support.design.a.isTextEmpty(v4_2)) {
                        return;
                    }

                    Long v5 = arg14.getAsLong("group_id");
                    if (v5 == null) {
                        return;
                    }

                    if (v5.longValue() <= 0) {
                        return;
                    }

                    v1 = Long.valueOf(0);
                    v2 = Integer.valueOf(0);
                    if (arg14.containsKey("item_id")) {
                        v1 = arg14.getAsLong("item_id");
                    }

                    if (arg14.containsKey("aggr_type")) {
                        v2 = arg14.getAsInteger("aggr_type");
                    }

                    Integer v6_1 = arg14.getAsInteger("target_type");
                    if (v6_1 == null) {
                        return;
                    }

                    if (v6_1.intValue() <= 0) {
                        return;
                    }

                    Long v7 = arg14.getAsLong("timestamp");
                    if (v7 == null) {
                        return;
                    }

                    if (v7.longValue() <= 0) {
                        return;
                    }

                    String v3_1 = arg14.getAsString("extra_data");
                    if (v3_1 == null) {
                        v3_1 = "";
                    }

                    if (v0 != 0) {
                        this.mSQLiteDatabase.delete("item_action_v3", "group_id=? AND item_id=? AND target_type=? AND action=? AND timestamp=?", new String[]{String.valueOf(v5), String.valueOf(v1), String.valueOf(v6_1), v4_2, String.valueOf(v7)});
                        return;
                    }

                    String[] v8 = new String[]{String.valueOf(v5), String.valueOf(v1), v4_2, String.valueOf(v6_1)};
                    arg14.clear();
                    arg14.put("timestamp", v7);
                    arg14.put("extra_data", v3_1);
                    if (this.mSQLiteDatabase.update("item_action_v3", arg14, "group_id=? AND item_id=? AND action=? AND target_type=?", v8) > 0) {
                        return;
                    }

                    arg14.put("group_id", v5);
                    arg14.put("item_id", v1);
                    arg14.put("aggr_type", v2);
                    arg14.put("action", v4_2);
                    arg14.put("target_type", v6_1);
                    this.mSQLiteDatabase.insert("item_action_v3", null, arg14);
                    break;
                }

            }
        }
    }

    public void a(int op_code, Object arg5) {
        switch (op_code) {
            case 10: {
                if ((arg5 instanceof List)) {
                    this.updateImpressionData(((List) arg5), true);
                }

                break;
            }
            default: {
                Logger.w("SSDBHelper", "unkown other op_code " + op_code);
                break;
            }
        }
    }

    public boolean isSQLiteDatabaseAvailable() {
        if (this.mSQLiteDatabase == null) {
            this.mSQLiteDatabase = this.createSQLiteDatabase(this.mContext);
        }

        if (this.mSQLiteDatabase == null || !this.mSQLiteDatabase.isOpen()) {
            Logger.w("SSDBHelper", "db not establish and open");
            return false;
        } else {
            return true;
        }
    }

    public void b(f arg1) {
    }

    public final String b(ItemType arg3) {
        String v0 = null;
        if (arg3 != null && this.a(arg3) != null) {
            v0 = "v30_article";
        }

        return v0;
    }

    public abstract SQLiteDatabase createSQLiteDatabase(Context context);

    public f b(long arg2) {
        return null;
    }

    public final void b(int arg4, Object arg5) {
        if (arg5 != null) {
            this.mAsyncOpHandler.sendMessage(this.mAsyncOpHandler.obtainMessage(11, arg4, 0, arg5));
        }
    }

    public final void deleteItemAction(List<ItemAction> itemActionList) {
        synchronized (this) {
            if (itemActionList != null) {

                if (itemActionList.isEmpty()) {
                    return;
                }

                if (!this.isSQLiteDatabaseAvailable()) {
                    return;
                }
                try {
                    this.mSQLiteDatabase.beginTransaction();
                    String whereClause = "item_id=? AND group_item_id=? AND action=? AND timestamp=?";
                    String[] whereArgs = new String[4];
                    ContentValues contentValues = new ContentValues();
                    Iterator<ItemAction> iterator = itemActionList.iterator();
                    while (iterator.hasNext()) {
                        ItemAction itemAction = iterator.next();
                        contentValues.clear();
                        whereArgs[0] = String.valueOf(itemAction.a.groupId);
                        whereArgs[1] = String.valueOf(itemAction.a.itemId);
                        whereArgs[2] = String.valueOf(itemAction.action);
                        whereArgs[3] = String.valueOf(itemAction.timestamp);
                        this.mSQLiteDatabase.delete("item_action", whereClause, whereArgs);
                    }
                    this.mSQLiteDatabase.setTransactionSuccessful();
                } catch (Exception exception) {
                    Logger.w("SSDBHelper", "confirm pending item action v2 exception: " + exception);
                } finally {
                    try {
                        this.mSQLiteDatabase.endTransaction();
                    } catch (Throwable throwable) {
                    }
                }
            }
        }
    }

    public final void deleteItemActionV3List(List<ItemActionV3> itemActionV3List) {
        synchronized (this) {
            if (itemActionV3List != null) {
                try {
                    if (itemActionV3List.isEmpty()) {
                        return;
                    }

                    if (!this.isSQLiteDatabaseAvailable()) {
                        return;
                    }

                    if (!this.isTableExists("item_action_v3")) {
                        return;
                    }
                    this.mSQLiteDatabase.beginTransaction();
                    String whereClause = "group_id=? AND item_id=? AND target_type=? AND action=? AND timestamp=?";
                    String[] whereArgs = new String[5];
                    ContentValues contentValues = new ContentValues();
                    Iterator<ItemActionV3> iterator = itemActionV3List.iterator();
                    while (iterator.hasNext()) {
                        ItemActionV3 itemActionV3 = iterator.next();
                        contentValues.clear();
                        whereArgs[0] = String.valueOf(itemActionV3.d.groupId);
                        whereArgs[1] = String.valueOf(itemActionV3.d.itemId);
                        whereArgs[2] = String.valueOf(itemActionV3.targetType);
                        whereArgs[3] = itemActionV3.action;
                        whereArgs[4] = String.valueOf(itemActionV3.timestamp);
                        this.mSQLiteDatabase.delete("item_action_v3", whereClause, whereArgs);
                    }
                    this.mSQLiteDatabase.setTransactionSuccessful();
                } catch (Exception exception) {
                    Logger.w("SSDBHelper", "confirm pending item action v3 exception: " + exception.toString());
                } finally {
                    try {
                        this.mSQLiteDatabase.endTransaction();
                    } catch (Exception e) {

                    }
                }
            }
        }
    }

    public final void f(List arg2) {
        if (!arg2.isEmpty()) {
            this.b(10, arg2);
        }
    }

    public final List<ItemAction> queryItemActionList(long timestamp) {
        Cursor cursor = null;
        ArrayList<ItemAction> result = null;
        synchronized (this) {
            try {
                result = new ArrayList();
                if (!this.isSQLiteDatabaseAvailable()) {
                    return result;
                }
                cursor = this.mSQLiteDatabase.query("item_action",
                        new String[]{"item_id", "group_item_id", "aggr_type", "action", "timestamp"},
                        "timestamp> ?", new String[]{String.valueOf(timestamp)}, null, null, "timestamp ASC", "200");
                while (cursor.moveToNext()) {
                    result.add(new ItemAction(new BaseArticle(cursor.getLong(0), cursor.getLong(1), cursor.getInt(2)), cursor.getInt(3), cursor.getLong(4)));
                }
                return result;
            } catch (Exception exception) {
                Logger.w("SSDBHelper", "get item action v2 exception: " + exception);
                return result;
            } finally {
                if (cursor != null) {
                    try {
                        cursor.close();
                    } catch (Throwable v0) {
                    }
                }
            }
        }
    }

    public final List<ItemActionV3> getPendingActionsV3(long timestamp) {
        Cursor cursor = null;
        ArrayList<ItemActionV3> result = null;
        synchronized (this) {
            try {
                result = new ArrayList();
                if (!this.isSQLiteDatabaseAvailable()) {
                    return result;
                }
                if (!this.isTableExists("item_action_v3")) {
                    return null;
                }
                cursor = this.mSQLiteDatabase.query("item_action_v3",
                        new String[]{"group_id", "item_id", "aggr_type", "target_type", "action", "timestamp", "extra_data"},
                        "timestamp> ?",
                        new String[]{String.valueOf(timestamp)},
                        null,
                        null,
                        "timestamp ASC",
                        "200");

                while (cursor.moveToNext()) {
                    result.add(new ItemActionV3(cursor.getString(4),
                            new BaseArticle(
                                    cursor.getLong(0),
                                    cursor.getLong(1),
                                    cursor.getInt(2)),
                            cursor.getInt(3),
                            cursor.getLong(5),
                            cursor.getString(6)));
                }
                return result;
            } catch (Exception exception) {
                Logger.w("SSDBHelper", "exception in getPendingActionsV3 : " + exception.toString());
                return result;
            } finally {
                if (cursor != null) {
                    try {
                        cursor.close();
                    } catch (Exception exception) {
                        Logger.e("SSDBHelper", "exception in getPendingActionsV3 when close dbcursor : " + exception.toString());
                    }
                }
            }
        }
    }

    public void handleMsg(Message message) {
        int v1_1;
        String v0_2;
        String v1;
        if (message.what == 10) {
            Object v0 = null;
            try {
                if ((message.obj instanceof ContentValues)) {
                    v0 = message.obj;
                }

                if (v0 != null && ((ContentValues) v0).size() >= 2 && (((ContentValues) v0).containsKey("ss_op_key"))) {
                    v1_1 = ((ContentValues) v0).getAsInteger("ss_op_key").intValue();
                    ((ContentValues) v0).remove("ss_op_key");
                    synchronized (this) {
                        if (this.isSQLiteDatabaseAvailable()) {
                            this.a(v1_1, ((ContentValues) v0));
                        }
                    }
                    return;
                }

                v1 = "SSDBHelper";
                if ("op action invalid: " + v0 == null) {
                    v0_2 = "null";
                } else {
                    v0_2 = v0.toString();
                    Logger.w(v1, v0_2);
                    return;
                }
                Logger.w(v1, v0_2);
                return;
            } catch (Exception v0_1) {
                Logger.w("SSDBHelper", "op action exception: " + v0_1);
                return;
            }


        }

        if (message.what != 11) {
            return;
        }

        if (message.obj == null) {
            return;
        }

        try {
            this.a(message.arg1, message.obj);
        } catch (Exception v0_1) {
            Logger.w("SSDBHelper", "other op action exception: " + v0_1);
        }
        return;
    }
}

